package com.mdp.workflow.de.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.mdp.workflow.api.DeploymentModelService;
import com.mdp.workflow.de.entity.Model;
import com.mdp.workflow.de.service.ModelServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value="/**/de/model")
@Api(tags={"act_de_model-操作接口"})
public class ModelController {
	
	static Logger logger =LoggerFactory.getLogger(ModelController.class);
	
	@Autowired
	private ModelServiceImpl modelService;

	@Autowired
	private DeploymentModelService deploymentModelService;

	@Value(value = "${mdp.platform-branch-id:platform-branch-001}")
	String platformBranchId;

	@ApiOperation( value = "act_de_model-查询列表",notes=" ")
	@ApiEntityParams(Model.class)
	@ApiResponses({
		@ApiResponse(code = 200,response=Model.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listModel(@ApiIgnore @RequestParam Map<String,Object> params){
		try {
			User user=LoginUtils.getCurrentUserInfo();
			QueryWrapper<Model> qw = QueryTools.initQueryWrapper(Model.class , params)
					.in("tenant_id",platformBranchId,user.getBranchId());
			IPage page=QueryTools.initPage(params);
			List<Map<String,Object>> datas = modelService.selectListMapByWhere(page,qw,params);
			for(Map<String,Object> model2: datas){
				model2.put("modelEditorJson","");
				model2.put("thumbnail", "");
			}
			return Result.ok("query-ok","查询成功").setData(datas).setTotal(page.getTotal());
		}catch (BizException e) {
			return Result.error(e);
		}catch (Exception e) {
			return Result.error(e);
		}
	}
	

	@ApiOperation( value = "act_de_model-新增",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=Model.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Result addModel(@RequestBody Model model) {
		 modelService.save(model);
         return Result.ok("add-ok","添加成功！");
	}

	@ApiOperation( value = "act_de_model-删除",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")
	}) 
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Result delModel(@RequestBody Model model){
		User user=LoginUtils.getCurrentUserInfo();
		String modelBranchId=model.getTenantId();
		if(!user.getBranchId().equals(modelBranchId)){
			return Result.error("tenant-id-not-platform-001","tenantId","该流程属于其它机构的流程模型，或者属于公共平台共享模型，你无权删除");
		}
		if(LoginUtils.hasAnyRoles("flowAdmin","platformAdmin")) {
			modelService.deleteByPk(model);
		}else{
			return Result.error("need-flowAdmin-or-platformAdmin","roles","该接口属于重大影响接口，需要流程管理员或者平台管理员才能操作");
		};
		modelService.removeById(model);
        return Result.ok("del-ok","删除成功！");
	}

	@ApiOperation( value = "act_de_model-修改",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=Model.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public Result editModel(@RequestBody Model model) {
		modelService.updateById(model);
        return Result.ok("edit-ok","修改成功！");
	}

    @ApiOperation( value = "act_de_model-批量修改某些字段",notes="")
    @ApiEntityParams( value = Model.class, props={ }, remark = "act_de_model", paramType = "body" )
	@ApiResponses({
			@ApiResponse(code = 200,response=Model.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	})
	@RequestMapping(value="/editSomeFields",method=RequestMethod.POST)
	public Result editSomeFields( @ApiIgnore @RequestBody Map<String,Object> params) {
        try{
            User user= LoginUtils.getCurrentUserInfo();
            modelService.editSomeFields(params);
            return Result.ok("edit-ok","更新成功");
        }catch (BizException e) {
            logger.error("",e);
            return Result.error(e);
        }catch (Exception e) {
            logger.error("",e);
            return Result.error(e);
        }
	}

	@ApiOperation( value = "act_de_model-批量删除",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")
	}) 
	@RequestMapping(value="/batchDel",method=RequestMethod.POST)
	public Result batchDelModel(@RequestBody List<Model> models) {
	    User user= LoginUtils.getCurrentUserInfo();
        try{ 
            if(models.size()<=0){
                return Result.error("model-batchDel-data-err-0","请上送待删除数据列表");
            }
             List<Model> datasDb=modelService.listByIds(models.stream().map(i-> i.getId() ).collect(Collectors.toList()));

            List<Model> can=new ArrayList<>();
            List<Model> no=new ArrayList<>();
            for (Model data : datasDb) {
                if(true){
                    can.add(data);
                }else{
                    no.add(data);
                } 
            }
            List<String> msgs=new ArrayList<>();
            if(can.size()>0){
                modelService.removeByIds(can);
                msgs.add(LangTips.transMsg("del-ok-num","成功删除%s条数据.",can.size()));
            }
    
            if(no.size()>0){ 
                msgs.add(LangTips.transMsg("not-allow-del-num","以下%s条数据不能删除:【%s】",no.size(),no.stream().map(i-> i.getId() ).collect(Collectors.joining(","))));
            }
            if(can.size()>0){
                 return Result.ok(msgs.stream().collect(Collectors.joining()));
            }else {
                return Result.error(msgs.stream().collect(Collectors.joining()));
            } 
        }catch (BizException e) { 
           return Result.error(e);
        }catch (Exception e) {
            return Result.error(e);
        }


	} 

	@ApiOperation( value = "act_de_model-根据主键查询一条数据",notes=" ")
     @ApiResponses({
            @ApiResponse(code = 200,response=Model.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
    })
    @RequestMapping(value="/queryById",method=RequestMethod.GET)
    public Result queryById(Model model) {
        Model data = (Model) modelService.getById(model);
        return Result.ok().setData(data);
    }

	/**
	 * 发布流程
	 */

	@RequestMapping(value="/deploy")
	public Result deployModel(@RequestBody com.mdp.workflow.de.entity.Model model) {

		try{
			if(LoginUtils.hasAnyRoles("flowAdmin","platformAdmin")) {
				deploymentModelService.modelDeployment(model.getId());
			}else{
				return Result.error("need-flowAdmin-or-platformAdmin","roles","该接口属于重大影响接口，需要流程管理员或者平台管理员才能操作");
			};
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}

		return Result.ok();
	}
	/**
	 * 发布流程
	 */

	@RequestMapping(value="/unDeploy")
	public Result unDeployModel(@RequestBody com.mdp.workflow.de.entity.Model model) {

		try{
			User user=LoginUtils.getCurrentUserInfo();
			String modelBranchId=model.getTenantId();
			if(!user.getBranchId().equals(modelBranchId)){
				return Result.error("tenant-id-not-platform-001","tenantId","该流程属于其它机构的流程模型，或者属于公共平台共享模型，你无权删除");
			}

			if(LoginUtils.hasAnyRoles("flowAdmin","platformAdmin")) {
				deploymentModelService.deleteDeployment(model.getModelKey());
			}else{
				return Result.error("need-flowAdmin-or-platformAdmin","roles","该接口属于重大影响接口，需要流程管理员或者平台管理员才能操作");
			};
			return Result.ok();
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}
}
